package com.orange.adminapi.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.orange.core.pojo.entity.user.UserCoupon;
import com.orange.core.pojo.enums.EPayStatus;
import com.orange.core.pojo.enums.EWriteOffStatus;
import com.orange.core.service.user.UserCouponService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Slf4j
@RequiredArgsConstructor
@Component
public class UserCouponTaskJobHandler {

    private final UserCouponService userCouponService;

    /**
     * 用户优惠券过期
     */
    @XxlJob("userCouponExpired")
    public ReturnT<String> userCouponExpired(String param) {
        log.info("开始执行用户优惠券过期任务");
        userCouponService.lambdaUpdate()
                .set(UserCoupon::getIsExpired, true)
                .eq(UserCoupon::getPayStatus, EPayStatus.PAID.getValue())
                .eq(UserCoupon::getWriteOffStatus, EWriteOffStatus.PENDING.getValue())
                .eq(UserCoupon::getIsExpired, false)
                .lt(UserCoupon::getEffectEnd, LocalDate.now())
                .update();
        log.info("用户优惠券过期任务执行完成");
        return ReturnT.SUCCESS;
    }

    /**
     * 删除用户未支付优惠券
     */
    @XxlJob("unpaidUserCouponDelete")
    public ReturnT<String> unpaidUserCouponDelete(String param) {
        log.info("开始删除用户未支付优惠券任务");
        userCouponService.remove(new LambdaQueryWrapper<UserCoupon>()
                .eq(UserCoupon::getPayStatus, EPayStatus.UNPAID.getValue())
                .lt(UserCoupon::getCreateTime, LocalDateTime.now().minusMinutes(30)));
        log.info("删除用户未支付优惠券任务完成");
        return ReturnT.SUCCESS;
    }
}
